import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:mobile_vpn/common/ext/asset_ext.dart';
import 'package:mobile_vpn/theme/color_palettes.dart';

import '../../../common/cpn/sliver_app_bar.dart';
import '../../../router/routers.dart';

class MemberExtensionPage extends StatefulWidget {
  @override
  _SingleMemberPageState createState() => _SingleMemberPageState();
}

class _SingleMemberPageState extends State<MemberExtensionPage> {
  // 定义模拟的会员数据
  static final List<MemberItem> mockMembers = [
    MemberItem(
      title: "会员类型A",
      price: 99.99,
      type: "1",
      discount: "8折",
    ),
    MemberItem(
      title: "会员类型B",
      price: 199.99,
      type: "2",
      discount: "7折",
    ),
    MemberItem(
      title: "会员类型C",
      price: 299.99,
      type: "1",
      discount: "6折",
    ),
  ];

  final Rx<MemberItem?> _selectedMemberItem = Rx<MemberItem?>(null);
  final Rx<String> _selectedPaymentMethod = 'wechat'.obs;

  @override
  void initState() {
    super.initState();
    _selectedMemberItem.value = mockMembers.first; // 默认选择第一个会员
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorPalettes.instance.background,
      body: CustomScrollView(
        slivers: [
          commonSliverAppBar(title: "会员"),
          SliverToBoxAdapter(
            child: _buildMemberContent(mockMembers),
          ),
        ],
      ),
    );
  }

  Widget _buildMemberContent(List<MemberItem> members) {
    return Column(
      children: [
        SizedBox(height: 30.h),
        _buildMemberCards(members),
        Obx(() => _selectedMemberItem.value != null
            ? _buildPaymentSection()
            : SizedBox.shrink()),
      ],
    );
  }

  Widget _buildMemberCards(List<MemberItem> members) {
    return SizedBox(
      height: 280.h,
      child: ScrollConfiguration(
        // 正确的参数名称是 'behavior' 而不是 'scrollBehavior'
        behavior: ScrollConfiguration.of(context).copyWith(
          dragDevices: {
            PointerDeviceKind.touch,
            PointerDeviceKind.mouse,
            PointerDeviceKind.stylus,
            PointerDeviceKind.trackpad,
          },
          scrollbars: false,
        ),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 30.w),
          clipBehavior: Clip.none,
          itemCount: members.length,
          physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
          itemBuilder: (context, index) {
            return Padding(
              padding: EdgeInsets.only(right: 30.w),
              child: Transform.translate(
                offset: Offset(0, 12.h),
                child: _buildMemberCard(members[index]),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildMemberCard(MemberItem member) {
    return GestureDetector(
      onTap: () => _selectedMemberItem.value = member,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            width: 260.w,
            padding: EdgeInsets.symmetric(vertical: 25.h, horizontal: 20.w),
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xFFCA7A95), // 统一颜色
                width: 3.w,
              ),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  member.title,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 34.sp,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 20.h),
                Text(
                  "USD ${member.price}",
                  style: TextStyle(
                    color: Color(0xFFBB6080), // 统一颜色
                    fontSize: 30.sp,
                  ),
                ),
                SizedBox(height: 10.h),
                Text(
                  '折合 USD ${(member.price / 30).toStringAsFixed(1)}/天',
                  style: TextStyle(
                    color: Color(0xFFBB6080), // 统一颜色
                    fontSize: 22.sp,
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            left: 4,
            top: 4,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 7.h),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.r),
                  bottomRight: Radius.circular(20.r),
                ),
                color: Color(0xFFFAEFF3), // 统一颜色
              ),
              child: Text(
                member.discount,
                style: TextStyle(
                  color: Color(0xFFBB6080), // 统一颜色
                  fontSize: 18.sp,
                ),
              ),
            ),
          ),
          Positioned(
            top: -12.h,
            left: 100.w,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.h),
              decoration: BoxDecoration(
                color: Color(0xFFFD0105),
                borderRadius: BorderRadius.circular(15.r),
              ),
              constraints: BoxConstraints(minWidth: 100.w),
              child: Center(
                child: Text(
                  "额外送7天",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildPaymentSection() {
    return SingleChildScrollView(
      child: Column(
        children: [
          SizedBox(height: 40.h),
          _buildSelectedPlanCard(),
          SizedBox(height: 40.h),
          _buildPaymentMethods(),
          SizedBox(height: 50.h),
          _buildSubscribeButton(),
          SizedBox(height: 30.h),
          _buildCustomerSupportText(),
        ],
      ),
    );
  }

  Widget _buildSelectedPlanCard() {
    return Obx(() {
      if (_selectedMemberItem.value == null) return SizedBox.shrink();

      final member = _selectedMemberItem.value!;
      return Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 30.w),
        padding: EdgeInsets.symmetric(vertical: 30.h, horizontal: 20.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.r),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              blurRadius: 15.r,
              offset: Offset(0, 5.h),
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.verified_rounded,
                  color: Color(0xFFBB6080), // 统一颜色
                  size: 36.sp,
                ),
                SizedBox(width: 10.w),
                Text(
                  '${member.title}',
                  style: TextStyle(
                    fontSize: 32.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ],
            ),
            SizedBox(height: 25.h),
            Text(
              'USD ${member.price}',
              style: TextStyle(
                fontSize: 44.sp,
                fontWeight: FontWeight.w900,
                color: Color(0xFFBB6080), // 统一颜色
              ),
            ),
            SizedBox(height: 15.h),
            Text(
              '≈ ${(member.price / 30).toStringAsFixed(1)}/天',
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      );
    });
  }

  Widget _buildPaymentMethods() {
    return Column(
      children: [
        _buildPaymentMethodCard(
          icon: "wechatpay".png,
          title: "微信支付",
          value: 'wechat',
        ),
        _buildPaymentMethodCard(
          icon: "alipaypayment".png,
          title: "支付宝",
          value: 'alipay',
        ),
      ],
    );
  }

  Widget _buildPaymentMethodCard({
    required String icon,
    required String title,
    required String value,
  }) {
    return Card(
      margin: EdgeInsets.zero,
      elevation: 2,
      color: Color(0xFFFFFFFF),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      child: Obx(() {
        final member = _selectedMemberItem.value;
        return Padding(
          padding: EdgeInsets.all(20.h),
          child: Row(
            children: [
              Image.asset(
                icon,
                width: 60.w,
                height: 60.h,
              ),
              SizedBox(width: 20.w),
              Text(
                title,
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Spacer(),
              Radio<String>(
                value: value,
                groupValue: _selectedPaymentMethod.value,
                onChanged: (v) => _selectedPaymentMethod.value = v!,
                fillColor: MaterialStateProperty.resolveWith<Color>((states) {
                  if (member == null) return Color(0xFF009FE8);
                  return Color(0xFFBB6080); // 统一颜色
                }),
              ),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildSubscribeButton() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 50.w),
      child: ElevatedButton(
        onPressed: () {},
        style: ElevatedButton.styleFrom(
          backgroundColor: Color(0xFF009FE8),
          minimumSize: Size(double.infinity, 90.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(45.r),
          ),
          elevation: 3,
        ),
        child: Text(
          '立即开通',
          style: TextStyle(
            fontSize: 34.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Widget _buildCustomerSupportText() {
    return Container(
      padding: EdgeInsets.only(bottom: 30.h),
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
              text: "支付遇到问题？联系",
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.grey[600],
              ),
            ),
            TextSpan(
              text: "在线客服",
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.blue,
                fontWeight: FontWeight.w500,
                decoration: TextDecoration.underline,
              ),
              recognizer: TapGestureRecognizer()
                ..onTap = () => AppRoutes.jumpPage(AppRoutes.contactServerPage),
            ),
            TextSpan(
              text: "获取帮助",
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class MemberItem {
  final String title;
  final double price;
  final String discount;
  final String type;

  MemberItem({
    required this.title,
    required this.price,
    required this.discount,
    required this.type,
  });
}
